<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="zh-CN">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">












<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />






















<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=6.0.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.0.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=6.0.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=6.0.4">


  <link rel="mask-icon" href="/images/logo.svg?v=6.0.4" color="#222">









<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '6.0.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  
  <meta name="keywords" content="mysql," />


<meta name="description" content="关系型数据库关系型数据库的三范式第一范式（1NF）: 每一列都是不可分割的原子数据项(基本类型列)  第二范式（2NF）： 要求实体的属性完全依赖于主关键字(无重复行)  第三范式（3NF）: 数据表不包含其它表已有的非主属性(无数据冗余) 关于数据库的规范设计，都会谈到是否符合三范式。但是考虑到数据库的性能优化，也不必都按照三范式来设计，可以做数据的适当冗余。如为了查询效率，在商品表，可以设置个">
<meta name="keywords" content="mysql">
<meta property="og:type" content="article">
<meta property="og:title" content="Mysql数据库学习总结">
<meta property="og:url" content="http://blog.yunshu168.com/posts/724b0e67.html">
<meta property="og:site_name" content="树下千云">
<meta property="og:description" content="关系型数据库关系型数据库的三范式第一范式（1NF）: 每一列都是不可分割的原子数据项(基本类型列)  第二范式（2NF）： 要求实体的属性完全依赖于主关键字(无重复行)  第三范式（3NF）: 数据表不包含其它表已有的非主属性(无数据冗余) 关于数据库的规范设计，都会谈到是否符合三范式。但是考虑到数据库的性能优化，也不必都按照三范式来设计，可以做数据的适当冗余。如为了查询效率，在商品表，可以设置个">
<meta property="og:locale" content="zh-CN">
<meta property="og:image" content="http://static.yunshudm.com/2017/3/wKiom1LUF8DS1inQAAE8bwOlNTY150.jpg">
<meta property="og:updated_time" content="2019-12-04T11:25:35.713Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Mysql数据库学习总结">
<meta name="twitter:description" content="关系型数据库关系型数据库的三范式第一范式（1NF）: 每一列都是不可分割的原子数据项(基本类型列)  第二范式（2NF）： 要求实体的属性完全依赖于主关键字(无重复行)  第三范式（3NF）: 数据表不包含其它表已有的非主属性(无数据冗余) 关于数据库的规范设计，都会谈到是否符合三范式。但是考虑到数据库的性能优化，也不必都按照三范式来设计，可以做数据的适当冗余。如为了查询效率，在商品表，可以设置个">
<meta name="twitter:image" content="http://static.yunshudm.com/2017/3/wKiom1LUF8DS1inQAAE8bwOlNTY150.jpg">






  <link rel="canonical" href="http://blog.yunshu168.com/posts/724b0e67.html"/>



<script type="text/javascript" id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>
  <title>Mysql数据库学习总结 | 树下千云</title>
  






  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?f8a99180bb75f49a4b2206cab6e25c50";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style type="text/css">
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion {
      .logo-line-before i { left: initial; }
      .logo-line-after i { right: initial; }
    }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <!-- <div class="headband"></div>
<a href="https://github.com/yunshu2009"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"></a> -->
    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"> <div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">树下千云</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-home"></i> <br />首页</a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-th"></i> <br />分类</a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />标签</a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            <i class="menu-item-icon fa fa-fw fa-user"></i> <br />关于</a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />搜索</a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>


  



 </div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://blog.yunshu168.com/posts/724b0e67.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="云舒">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="树下千云">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Mysql数据库学习总结</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <!--<span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>-->
              
                <!--<span class="post-meta-item-text">发表于</span>-->
              
              <!--<time title="创建于" itemprop="dateCreated datePublished" datetime="2018-03-20T19:47:21+08:00">2018-03-20</time>-->
            

            
            

            
          </span>

          

          
            
          

          
          

          


          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="关系型数据库"><a href="#关系型数据库" class="headerlink" title="关系型数据库"></a>关系型数据库</h2><h3 id="关系型数据库的三范式"><a href="#关系型数据库的三范式" class="headerlink" title="关系型数据库的三范式"></a>关系型数据库的三范式</h3><p>第一范式（1NF）: 每一列都是不可分割的原子数据项(基本类型列) </p>
<p>第二范式（2NF）： 要求实体的属性完全依赖于主关键字(无重复行) </p>
<p>第三范式（3NF）: 数据表不包含其它表已有的非主属性(无数据冗余)</p>
<p>关于数据库的规范设计，都会谈到是否符合三范式。但是考虑到数据库的性能优化，也不必都按照三范式来设计，可以做数据的适当冗余。如为了查询效率，在商品表，可以设置个img_url字段放图片的主图。</p>
<a id="more"></a>
<h2 id="MySQL本质了解"><a href="#MySQL本质了解" class="headerlink" title="MySQL本质了解"></a>MySQL本质了解</h2><h3 id="mysql逻辑架构"><a href="#mysql逻辑架构" class="headerlink" title="mysql逻辑架构"></a>mysql逻辑架构</h3><p><img src="http://static.yunshudm.com/2017/3/wKiom1LUF8DS1inQAAE8bwOlNTY150.jpg" alt="mysql"></p>
<p>1.最上层是一些客户端和连接服务，包含本地sock通信和大多数基于客户端/服务端工具实现的类似于tcp/ip的通信。主要完成一些类似于连接处理、授权认证、及相关的安全方案。在该层上引入了线程池的概念，为通过认证安全接入的客户端提供线程。同样在该层上可以实现基于SSL的安全链接。服务器也会为安全接入的每个客户端验证它所具有的操作权限。</p>
<p>2.第二层架构主要完成大多的核心服务功能，如SQL接口，并完成缓存的查询，SQL的分析和优化及部分内置函数的执行。所有跨存储引擎的功能也在这一层实现，如过程、函数等。在该层，服务器会解析查询并创建相应的内部解析树，并对其完成相应的优化如确定查询表的顺序，是否利用索引等，最后生成相应的执行操作。如果是select语句，服务器还会查询内部的缓存。如果缓存空间足够大，这样在解决大量读操作的环境中能够很好的提升系统的性能。</p>
<p>3.存储引擎层，存储引擎真正的负责了MySQL中数据的存储和提取，服务器通过API与存储引擎进行通信。不同的存储引擎具有的功能不同，这样我们可以根据自己的实际需要进行选取。</p>
<p>4.数据存储层，主要是将数据存储在运行于裸设备的文件系统之上，并完成与存储引擎的交互。</p>
<h4 id="MySQL核心模块"><a href="#MySQL核心模块" class="headerlink" title="MySQL核心模块"></a>MySQL核心模块</h4><pre>
• Server Initialization Module 命令行、配置文件解析、内存分配
• Connection Manager 协议监听和协议转发
• Thread Manager 新建线程处理请求
• Connection Thread 新建新的,或者从线程缓存中去取
• User Authentication Module 验证用户身份
• Access Control Module  访问控制
• Parser 接收请求,解析进入命令分发或者进入查询
• Command Dispatcher 解析器分发给命令分发器
• Query Cache Module 查询缓存检查(SELECT、DELETE、UPDATE)
• Optimizer 查询优化器
• Table Manager 打开表,获取锁
• Table Modification Modules 表更新
• Table Maintenance Module 表维护
• Status Reporting Module 状态报告
• Abstracted Storage Engine Interface (Table Handler) 抽象引擎接口
• Storage Engine Implementations (MyISAM, InnoDB...) 存储引擎实现
• Logging Module 日志记录
• Replication Master Module 复制主模块
• Replication Slave Module 复制从模块
• Client/Server Protocol API 客户端、服务器协议 API
• Low-Level Network I/O API 底层网络 I/O API
• Core API 核心 API
</pre>

<h4 id="存储引擎的区别和选择"><a href="#存储引擎的区别和选择" class="headerlink" title="存储引擎的区别和选择"></a>存储引擎的区别和选择</h4><p>存储引擎是mysql提供的文件访问层的一个抽象接口来定制一种文件访问机制。 </p>
<p>mysql的存储引擎包括:MyISAM、InnoDB、BDB、MEMORY、MERGE、<br>EXAMPLE、NDBCluster、ARCHIVE、CSV、BLACKHOLE、FEDERATED等。</p>
<p>MyISAM:不支持事务,支持全文索引,表级锁；数据文件全量备份，可以直接拷贝数据文件进行备份；适合处理读频率远大于写频率的静态表。</p>
<p>InnoDB:支持事务,5.6以后支持全文索引,默认行级锁；数据文件两种形式(单一文件形式和多文件形式,以共享表空间与独占表空间存储)；适用于高并发读写。</p>
<h5 id="MySQL-InnoDB的存储文件"><a href="#MySQL-InnoDB的存储文件" class="headerlink" title="MySQL InnoDB的存储文件"></a>MySQL InnoDB的存储文件</h5><p>参考：<a href="http://blog.csdn.net/chenjiayi_yun/article/details/45533909" target="_blank" rel="noopener">http://blog.csdn.net/chenjiayi_yun/article/details/45533909</a></p>
<h3 id="MySQL插件"><a href="#MySQL插件" class="headerlink" title="MySQL插件"></a>MySQL插件</h3><p>NoSql 插件 HandlerSocket</p>
<p>中文全文索引插件 mysqlcft （mysql5.7内置有n-gram parser插件）</p>
<p>InnoDB引擎中的Memcached插件</p>
<h3 id="MySQL中的事务"><a href="#MySQL中的事务" class="headerlink" title="MySQL中的事务"></a>MySQL中的事务</h3><p>事务的ACID:<br>• 原子性(Atomicity ) 全部执行或全部不执行</p>
<p>• 一致性( Consistency ) 事务前后数据都是一致性状态,约束等</p>
<p>• 隔离性或独立性( Isolation) 事务之间是独立的,和级别相关</p>
<p>• 持久性(Durabilily) 事务完成即持久化存储</p>
<h3 id="MysSQL锁表类型"><a href="#MysSQL锁表类型" class="headerlink" title="MysSQL锁表类型"></a>MysSQL锁表类型</h3><p>1- 表级锁(MyISAM)</p>
<p>开销小,加锁快;不会出现死锁;锁定粒 度大,发生锁冲突的概率最高,并发度最低</p>
<p>可以通过检查table_locks_waited和table_locks_immediate状态变量来分析系统上的表锁定争夺：</p>
<pre>
mysql> show status like 'table%';
+-----------------------+-------+
| Variable_name         | Value |
+-----------------------+-------+
| Table_locks_immediate | 2979  |
| Table_locks_waited    | 0     |
+-----------------------+-------+
2 rows in set (0.00 sec))
</pre>

<p>如果Table_locks_waited的值比较高，则说明存在着较严重的表级锁争用情况。</p>
<p>MySQL的表级锁有两种模式：表共享读锁（Table Read Lock）和表独占写锁（Table Write Lock）。锁模式的兼容性如表20-1所示。</p>
<p>MySQL中的表锁兼容性    </p>
<table>
<thead>
<tr>
<th>请求锁模式 是否兼容 当前锁模式</th>
<th>None</th>
<th>读锁</th>
<th>写锁</th>
</tr>
</thead>
<tbody>
<tr>
<td>读锁</td>
<td>是</td>
<td>是</td>
<td>否 </td>
</tr>
<tr>
<td>写锁</td>
<td>是</td>
<td>否</td>
<td>否    </td>
</tr>
</tbody>
</table>
<ul>
<li>行级锁(InnoDB)</li>
</ul>
<p>开销大,加锁慢;会出现死锁;锁定粒度最 小,发生锁冲突的概率最低,并发度也最高</p>
<p>可以通过检查InnoDB_row_lock状态变量来分析系统上的行锁的争夺情况：</p>
<pre>
mysql> show status like 'innodb_row_lock%';
+-------------------------------+-------+
| Variable_name                 | Value |
+-------------------------------+-------+
| InnoDB_row_lock_current_waits | 0     |
| InnoDB_row_lock_time          | 0     |
| InnoDB_row_lock_time_avg      | 0     |
| InnoDB_row_lock_time_max      | 0     |
| InnoDB_row_lock_waits         | 0     |
+-------------------------------+-------+
5 rows in set (0.01 sec)
</pre>

<p>如果发现锁争用比较严重，如InnoDB_row_lock_waits和InnoDB_row_lock_time_avg的值比较高，还可以通过设置InnoDB Monitors来进一步观察发生锁冲突的表、数据行等，并分析锁争用的原因。</p>
<ul>
<li>页面锁</li>
</ul>
<p>开销和加锁时间界于表锁和行锁之间;会出现死锁;锁定 粒度界于表锁和行锁之间,并发度一般</p>
<h3 id="使用悲观锁和乐观锁解决并发"><a href="#使用悲观锁和乐观锁解决并发" class="headerlink" title="使用悲观锁和乐观锁解决并发"></a>使用悲观锁和乐观锁解决并发</h3><h4 id="悲观锁"><a href="#悲观锁" class="headerlink" title="悲观锁"></a>悲观锁</h4><p>在关系数据库管理系统里，悲观并发控制（又名“悲观锁”，Pessimistic Concurrency Control，缩写“PCC”）是一种并发控制的方法。它可以阻止一个事务以影响其他用户的方式来修改数据。如果一个事务执行的操作都某行数据应用了锁，那只有当这个事务把锁释放，其他事务才能够执行与该锁冲突的操作。<br>悲观并发控制主要用于数据争用激烈的环境，以及发生并发冲突时使用锁保护数据的成本要低于回滚事务的成本的环境中。</p>
<p>在DBMS中，悲观锁正是利用数据库本身提供的锁机制来实现的。</p>
<h4 id="乐观锁"><a href="#乐观锁" class="headerlink" title="乐观锁"></a>乐观锁</h4><p>乐观锁（ Optimistic Locking ） 相对悲观锁而言，乐观锁假设认为数据一般情况下不会造成冲突，所以在数据进行提交更新的时候，才会正式对数据的冲突与否进行检测，如果发现冲突了，则让返回用户错误的信息，让用户决定如何去做。</p>
<p>参考：</p>
<ul>
<li><p><a href="http://chenzhou123520.iteye.com/blog/1860954" target="_blank" rel="noopener">mysql悲观锁总结和实践</a></p>
</li>
<li><p><a href="http://chenzhou123520.iteye.com/blog/1863407" target="_blank" rel="noopener">mysql乐观锁总结和实践</a></p>
</li>
<li><p><a href="http://www.hollischuang.com/archives/934" target="_blank" rel="noopener">深入理解乐观锁与悲观锁</a></p>
</li>
</ul>
<h2 id="海量数据的分页优化"><a href="#海量数据的分页优化" class="headerlink" title="海量数据的分页优化"></a>海量数据的分页优化</h2><h3 id="方案"><a href="#方案" class="headerlink" title="方案"></a>方案</h3><ol>
<li>建立合适的索引</li>
<li>使用Redis缓存count,根据访问热度缓存靠后的分页数据</li>
<li>查找出limit的开始行id，然后用where拼接，如：<code>where id&gt;*** limit 0,99</code></li>
<li>产品设计优化</li>
</ol>
<h2 id="MySQL的安装与配置"><a href="#MySQL的安装与配置" class="headerlink" title="MySQL的安装与配置"></a>MySQL的安装与配置</h2><h3 id="MySQL源码安装"><a href="#MySQL源码安装" class="headerlink" title="MySQL源码安装"></a>MySQL源码安装</h3><p>下面在CentOS环境下安装、参考Oneinstack</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"># 下载mysql源码包</span><br><span class="line">wget -4 --tries=6 -c --no-check-certificate https://mirrors.tuna.tsinghua.edu.cn/mysql/downloads/MySQL-5.7/mysql-5.7.21.tar.gz</span><br><span class="line"># 进入软件目录</span><br><span class="line">pushd /opt/software/src</span><br><span class="line"># 添加mysql用户</span><br><span class="line">useradd -M -s /sbin/nologin mysql</span><br><span class="line"># 创建mysql的安装目录</span><br><span class="line">mkdir -p /usr/local/mysql</span><br><span class="line"># 创建mysql data目录</span><br><span class="line">mkdir -p /data/mysql</span><br><span class="line"># 更改mysql data目录权限</span><br><span class="line">chown mysql.mysql -R /data/mysql</span><br><span class="line">tar xzf mysql-5.7.21.tar.gz</span><br><span class="line">pushd mysql-5.7.21</span><br><span class="line">cmake . -DCMAKE_INSTALL_PREFIX=/usr/local/mysql</span><br><span class="line">    -DMYSQL_DATADIR=/data/mysql \</span><br><span class="line">    -DSYSCONFDIR=/etc \</span><br><span class="line">    -DWITH_INNOBASE_STORAGE_ENGINE=1 \</span><br><span class="line">    -DWITH_PARTITION_STORAGE_ENGINE=1 \</span><br><span class="line">    -DWITH_FEDERATED_STORAGE_ENGINE=1 \</span><br><span class="line">    -DWITH_BLACKHOLE_STORAGE_ENGINE=1 \</span><br><span class="line">    -DWITH_MYISAM_STORAGE_ENGINE=1 \</span><br><span class="line">    -DWITH_EMBEDDED_SERVER=1 \</span><br><span class="line">    -DENABLE_DTRACE=0 \</span><br><span class="line">    -DENABLED_LOCAL_INFILE=1 \</span><br><span class="line">    -DDEFAULT_CHARSET=utf8mb4 \</span><br><span class="line">    -DDEFAULT_COLLATION=utf8mb4_general_ci \</span><br><span class="line">    -DEXTRA_CHARSETS=all \</span><br><span class="line">    -DCMAKE_EXE_LINKER_FLAGS=&apos;-ljemalloc&apos;</span><br><span class="line">make</span><br><span class="line">make install</span><br><span class="line">popd</span><br><span class="line">rm -rf mysql-5.7.21</span><br><span class="line">cp /usr/local/mysql/support-files/mysql.server /etc/init.d/mysqld</span><br><span class="line">sed -i &quot;s@^basedir=.*@basedir=/usr/local/mysql@&quot; /etc/init.d/mysqld</span><br><span class="line">sed -i &quot;s@^datadir=.*@datadir=/data/mysql@&quot; /etc/init.d/mysqld</span><br><span class="line">chmod +x /etc/init.d/mysqld</span><br><span class="line">chkconfig --add mysqld</span><br><span class="line">chkconfig mysqld on</span><br><span class="line"># 添加mysql配置</span><br><span class="line"> cat &gt; /etc/my.cnf &lt;&lt; EOF</span><br><span class="line">[client]</span><br><span class="line">port = 3306</span><br><span class="line">socket = /tmp/mysql.sock</span><br><span class="line">default-character-set = utf8mb4</span><br><span class="line">[mysql]</span><br><span class="line">prompt=&quot;MySQL [\\d]&gt; &quot;</span><br><span class="line">no-auto-rehash</span><br><span class="line">[mysqld]</span><br><span class="line">port = 3306</span><br><span class="line">socket = /tmp/mysql.sock</span><br><span class="line">basedir = /usr/local/mysql</span><br><span class="line">datadir = /data/mysql</span><br><span class="line">pid-file = /data/mysql/mysql.pid</span><br><span class="line">user = mysql</span><br><span class="line">bind-address = 0.0.0.0</span><br><span class="line">server-id = 1</span><br><span class="line">init-connect = &apos;SET NAMES utf8mb4&apos;</span><br><span class="line">character-set-server = utf8mb4</span><br><span class="line">skip-name-resolve</span><br><span class="line">#skip-networking</span><br><span class="line">back_log = 300</span><br><span class="line">max_connections = 1000</span><br><span class="line">max_connect_errors = 6000</span><br><span class="line">open_files_limit = 65535</span><br><span class="line">table_open_cache = 128</span><br><span class="line">max_allowed_packet = 500M</span><br><span class="line">binlog_cache_size = 1M</span><br><span class="line">max_heap_table_size = 8M</span><br><span class="line">tmp_table_size = 16M</span><br><span class="line">read_buffer_size = 2M</span><br><span class="line">read_rnd_buffer_size = 8M</span><br><span class="line">sort_buffer_size = 8M</span><br><span class="line">join_buffer_size = 8M</span><br><span class="line">key_buffer_size = 4M</span><br><span class="line">thread_cache_size = 8</span><br><span class="line">query_cache_type = 1</span><br><span class="line">query_cache_size = 8M</span><br><span class="line">query_cache_limit = 2M</span><br><span class="line">ft_min_word_len = 4</span><br><span class="line">log_bin = mysql-bin</span><br><span class="line">binlog_format = mixed</span><br><span class="line">expire_logs_days = 7</span><br><span class="line">log_error = /dta/mysql/mysql-error.log</span><br><span class="line">slow_query_log = 1</span><br><span class="line">long_query_time = 1</span><br><span class="line">slow_query_log_file = /data/mysql/mysql-slow.log</span><br><span class="line">performance_schema = 0</span><br><span class="line">explicit_defaults_for_timestamp</span><br><span class="line">#lower_case_table_names = 1</span><br><span class="line">skip-external-locking</span><br><span class="line">default_storage_engine = InnoDB</span><br><span class="line">#default-storage-engine = MyISAM</span><br><span class="line">innodb_file_per_table = 1</span><br><span class="line">innodb_open_files = 500</span><br><span class="line">innodb_buffer_pool_size = 64M</span><br><span class="line">innodb_write_io_threads = 4</span><br><span class="line">innodb_read_io_threads = 4</span><br><span class="line">innodb_thread_concurrency = 0</span><br><span class="line">innodb_purge_threads = 1</span><br><span class="line">innodb_flush_log_at_trx_commit = 2</span><br><span class="line">innodb_log_buffer_size = 2M</span><br><span class="line">innodb_log_file_size = 32M</span><br><span class="line">innodb_log_files_in_group = 3</span><br><span class="line">innodb_max_dirty_pages_pct = 90</span><br><span class="line">innodb_lock_wait_timeout = 120</span><br><span class="line">bulk_insert_buffer_size = 8M</span><br><span class="line">myisam_sort_buffer_size = 8M</span><br><span class="line">myisam_max_sort_file_size = 10G</span><br><span class="line">myisam_repair_threads = 1</span><br><span class="line">interactive_timeout = 28800</span><br><span class="line">wait_timeout = 28800</span><br><span class="line">[mysqldump]</span><br><span class="line">quick</span><br><span class="line">max_allowed_packet = 500M</span><br><span class="line">[myisamchk]</span><br><span class="line">key_buffer_size = 8M</span><br><span class="line">sort_buffer_size = 8M</span><br><span class="line">read_buffer = 4M</span><br><span class="line">write_buffer = 4M</span><br><span class="line">EOF</span><br><span class="line"># 数据库初始化</span><br><span class="line">/usr/local/mysql/bin/mysqld --initialize-insecure --user=mysql --basedir=/usr/local/mysql --datadir=/data/mysql</span><br><span class="line">chown mysql.mysql -R /data/mysql</span><br><span class="line">service mysqld start</span><br><span class="line"># 设置环境变量</span><br><span class="line">echo &quot;export PATH=/usr/local/mysql/bin:\$PATH&quot; &gt;&gt; /etc/profile</span><br><span class="line">[ -z &quot;$(grep ^&apos;export PATH=&apos; /etc/profile)&quot; ] &amp;&amp; echo &quot;export PATH=/usr/local/mysql/bin:\$PATH&quot; &gt;&gt; /etc/profile</span><br><span class="line">[ -n &quot;$(grep ^&apos;export PATH=&apos; /etc/profile)&quot; -a -z &quot;$(grep /usr/local/mysql /etc/profile)&quot; ] &amp;&amp; sed -i &quot;s@^export PATH=\(.*\)@export PATH=/usr/local/mysql/bin:\1@&quot; /etc/profile</span><br><span class="line"># 设置密码</span><br><span class="line">/usr/local/mysql/bin/mysql -e &quot;grant all privileges on *.* to root@&apos;127.0.0.1&apos; identified by &quot;123456&quot; with grant option;&quot;</span><br><span class="line">/usr/local/mysql/bin/mysql -e &quot;grant all privileges on *.* to root@&apos;localhost&apos; identified by &quot;123456&quot; with grant option;&quot;</span><br><span class="line"># 添加动态链接库</span><br><span class="line">echo &quot;/usr/local/mysql/lib&quot; &gt; /etc/ld.so.conf.d/mysql.conf</span><br><span class="line">ldconfig</span><br><span class="line">service mysqld restart</span><br></pre></td></tr></table></figure>
<h3 id="MySQL源码目录"><a href="#MySQL源码目录" class="headerlink" title="MySQL源码目录"></a>MySQL源码目录</h3><pre>
• BUILD 编译脚本
• client 命令行工具代码(mysql,mysqladmin)
• cmd-line-utils 增强命令行的第三方库 (libedit 如 readline).
• dbug 调试库
• libevent 由于 5.6 支持 某个插件的库
• plugin 插件所在的库
• libmysql MySQL 的库,其他客户端,经如C/PHP 访问MySQL需
要引用这个目录的库
• mysys 核心可移植性或者工具API
• regex 正则表达式库
• scripts 脚本库,如 mysqld_safe 所在
• sql MySQL 的核心所在,用C++所写
• sql-common 客户端、服务器能用代码
• strings 字符串库
• storage 存储引擎所在的库
• vio 底层网络I/O操作库
• zlib库
</pre>

<h3 id="数据库配置优化"><a href="#数据库配置优化" class="headerlink" title="数据库配置优化"></a>数据库配置优化</h3><h4 id="基础配置"><a href="#基础配置" class="headerlink" title="基础配置"></a>基础配置</h4><h5 id="连接数配置"><a href="#连接数配置" class="headerlink" title="连接数配置"></a>连接数配置</h5><p>通过<code>show variables like &#39;%conn%&#39;;</code>查看配置</p>
<ul>
<li>max_connections 设置整个服务器最大session连接数</li>
<li>max_user_connections   每个用户的session连接个数,值为0时表示每个用户的连接数不受限制</li>
</ul>
<h5 id="网络配置"><a href="#网络配置" class="headerlink" title="网络配置"></a>网络配置</h5><p>skip-name-resolve：禁止掉DNS的查询</p>
<blockquote>
<p>解释：<br>mysql会在用户登录过程中对客户端IP进行DNS反查，不管你是使用IP登录还是域名登录，这个反查的过程都是在的。所以如果你的mysql所在的服务器的DNS有问题或者质量不好，那么就有可能造成127.0.0.1登录很快，用域名或者IP登录数据库很慢的DNS解析问题。</p>
<p>数据库加这个参数速度会变快skip-name-resolve，但是也有注意点，mysql.user 表里面的host不要用localhost之类的，要用127.0.0.1，不然连自己都连不上数据库，会报错。</p>
</blockquote>
<h4 id="缓存配置"><a href="#缓存配置" class="headerlink" title="缓存配置"></a>缓存配置</h4><h5 id="查询缓存"><a href="#查询缓存" class="headerlink" title="查询缓存"></a>查询缓存</h5><p>查询缓存的作用就是当查询接收到一个和之前同样的查询，服务器将会从查询缓存种检索结果，而不是再次分析和执行上次的查询。这样就大大提高了性能，节省时间。当查询很大、更新很少的情况下可以使用查询缓存。</p>
<p>查看缓存设置<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">show variables like &apos;%query_cache%&apos;;</span><br></pre></td></tr></table></figure></p>
<p>输出如下：</p>
<pre>
+------------------------------+---------+
| Variable_name                | Value   |
+------------------------------+---------+
| have_query_cache             | YES     |
| query_cache_limit            | 1048576 |
| query_cache_min_res_unit     | 4096    |
| query_cache_size             | 1048576 |
| query_cache_type             | OFF     |
| query_cache_wlock_invalidate | OFF     |
+------------------------------+---------+
</pre>


<p>查看缓存的状态<br>使用<code>show status like &#39;%Qcache%&#39;;</code></p>
<p>输出结果：</p>
<pre>
+-------------------------+---------+
| Variable_name           | Value   |
+-------------------------+---------+
| Qcache_free_blocks      | 1       |
| Qcache_free_memory      | 1031832 |
| Qcache_hits             | 0       |
| Qcache_inserts          | 0       |
| Qcache_lowmem_prunes    | 0       |
| Qcache_not_cached       | 4       |
| Qcache_queries_in_cache | 0       |
| Qcache_total_blocks     | 1       |
+-------------------------+---------+
</pre>


<p>参考：<br><a href="https://blog.csdn.net/qq_27238185/article/details/54096069" target="_blank" rel="noopener">mysql查询缓存打开、设置、参数查询、性能变量意思</a></p>
<h4 id="日志配置"><a href="#日志配置" class="headerlink" title="日志配置"></a>日志配置</h4><h5 id="通用查询日志"><a href="#通用查询日志" class="headerlink" title="通用查询日志"></a>通用查询日志</h5><p>通用查询日志：记录建立的客户端连接和执行的语句</p>
<p>1). 查看通用查询日志配置<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">show variables like &apos;%general%&apos;;</span><br></pre></td></tr></table></figure></p>
<p>输出结果：</p>
<pre>
+------------------+------------------------------+
| Variable_name    | Value                        |
+------------------+------------------------------+
| general_log      | OFF                          |
| general_log_file | /data/mysql/xxxxxx.log       |
+------------------+------------------------------+
</pre>
通用查询日志默认是关闭的。

2). 查看当前日志输出的格式

<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">MySQL [(none)]&gt; show variables like &apos;%log_output%&apos;;</span><br></pre></td></tr></table></figure>

输出结果：
<pre>
+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| log_output    | FILE  |
+---------------+-------+
1 row in set (0.01 sec)
</pre>

<p>日志格式可以是FILE（存储在数数据库的数据文件中的hostname.log），也可以是TABLE（存储在数据库中的mysql.general_log）</p>
<p>3) 开启通用查询日志的方式</p>
<ul>
<li>通过set命令设置，只对当前mysql生效，重启失效</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">set global general_log=on;</span><br><span class="line">set global log_output=&apos;TABLE&apos;;   # 值为“FILE”、“TABLE“或者“FILE,TABLE”</span><br></pre></td></tr></table></figure>
<ul>
<li>通过配置文件my.cnf配置</li>
</ul>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">general_log=1  # 为1表示开启通用日志查询，值为0表示关闭通用日志查询</span><br><span class="line">log_output=FILE,TABLE # 设置通用日志的输出格式为文件和表</span><br></pre></td></tr></table></figure>
<h5 id="慢查询日志"><a href="#慢查询日志" class="headerlink" title="慢查询日志"></a>慢查询日志</h5><p>MySQL的慢查询日志是MySQL提供的一种日志记录，用来记录在MySQL中响应时间超过阈值的语句，具体指运行时间超过long_query_time值的SQL，则会被记录到慢查询日志中（日志可以写入文件或者数据库表，如果对性能要求高的话，建议写文件）。默认情况下，MySQL数据库是不开启慢查询日志的，long_query_time的默认值为10（即10秒，通常设置为1秒），即运行10秒以上的语句是慢查询语句。</p>
<p>1) 查看是否开启慢查询日志</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">show variables like &apos;%quer%&apos;;</span><br></pre></td></tr></table></figure>
<p>输出结果中</p>
<ul>
<li>slow_query_log值为ON时表示开启</li>
<li>slow_query_log_file 的值是记录的慢查询日志到文件中（注意：默认名为主机名.log，慢查询日志是否写入指定文件中，需要指定慢查询的输出日志格式为文件，相关命令为：show variables like ‘%log_output%’；去查看输出的格式。当设置为TABLE时，慢查询日志输出至mysql.slow_log中）</li>
</ul>
<p>2) 在配置文件中配置慢查询</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">slow_query_log = 1</span><br><span class="line">long_query_time = 1</span><br><span class="line">slow_query_log_file = /data/mysql/mysql-slow.log</span><br></pre></td></tr></table></figure>
<p>3) 如何制造慢查询，看慢查询设置是否有效</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&gt; select sleep(5)</span><br></pre></td></tr></table></figure>
<h5 id="二进制配置"><a href="#二进制配置" class="headerlink" title="二进制配置"></a>二进制配置</h5><p>主要作数据库的恢复和同步使用</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">log_bin = mysql-bin</span><br><span class="line">binlog_format = mixed</span><br><span class="line">expire_logs_days = 7</span><br></pre></td></tr></table></figure>
<h5 id="错误日志"><a href="#错误日志" class="headerlink" title="错误日志"></a>错误日志</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">log_error = /data/mysql/mysql-error.log</span><br></pre></td></tr></table></figure>
      
    </div>

    

    
    
    
<div>
  
    <div>
    
        <div style="text-align:center;color: #ccc;font-size:14px;">------本文结束<i class="fa fa-paw"></i>感谢阅读------</div>
    
</div>
  
</div>
    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>欣赏此文？求鼓励，求支持！</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechat.png" alt="云舒 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.png" alt="云舒 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>云舒</li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://blog.yunshu168.com/posts/724b0e67.html" title="Mysql数据库学习总结">http://blog.yunshu168.com/posts/724b0e67.html</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明出处！</li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/mysql/" rel="tag"># mysql</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/26645fa0.html" rel="next" title="使用swoole定时器监控服务的运行">
                <i class="fa fa-chevron-left"></i> 使用swoole定时器监控服务的运行
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/c8d87eec.html" rel="prev" title="网站性能优化">
                网站性能优化 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        
  <div class="bdsharebuttonbox">
    <a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a>
    <a href="#" class="bds_douban" data-cmd="douban" title="分享到豆瓣网"></a>
    <a href="#" class="bds_sqq" data-cmd="sqq" title="分享到QQ好友"></a>
    <a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间"></a>
    <a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信"></a>
    <a href="#" class="bds_tieba" data-cmd="tieba" title="分享到百度贴吧"></a>
    <a href="#" class="bds_twi" data-cmd="twi" title="分享到Twitter"></a>
    <a href="#" class="bds_fbook" data-cmd="fbook" title="分享到Facebook"></a>
    <a href="#" class="bds_more" data-cmd="more"></a>
    <a class="bds_count" data-cmd="count"></a>
  </div>
  <script>
    window._bd_share_config = {
      "common": {
        "bdText": "",
        "bdMini": "2",
        "bdMiniList": false,
        "bdPic": ""
      },
      "share": {
        "bdSize": "16",
        "bdStyle": "0"
      },
      "image": {
        "viewList": ["tsina", "douban", "sqq", "qzone", "weixin", "twi", "fbook"],
        "viewText": "分享到：",
        "viewSize": "16"
      }
    }
  </script>

<script>
  with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='//bdimg.share.baidu.com/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];
</script>

      
    </div>
  </div>


          </div>
          

  
    <div class="comments" id="comments">
      
        <div id="gitment-container"></div>
      
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.jpg"
                alt="云舒" />
            
              <p class="site-author-name" itemprop="name">云舒</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives">
                
                    <span class="site-state-item-count">68</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">5</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">28</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  <a href="https://github.com/yunshu2009" target="_blank" title="GitHub"><i class="fa fa-fw fa-github"></i>GitHub</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:yunshu.luo@gmail.com" target="_blank" title="E-Mail"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.cnblogs.com/luoyunshu/" target="_blank" title="Cnblogs"><i class="fa fa-fw fa-globe"></i>Cnblogs</a>
                  
                </span>
              
                <span class="links-of-author-item">
                  <a href="https://www.bilibili.com" target="_blank" title="bilibili"><i class="fa fa-fw fa-globe"></i>bilibili</a>
                  
                </span>
              
            </div>
          

          
          

          
          

          
            
          
          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#关系型数据库"><span class="nav-number">1.</span> <span class="nav-text">关系型数据库</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#关系型数据库的三范式"><span class="nav-number">1.1.</span> <span class="nav-text">关系型数据库的三范式</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#MySQL本质了解"><span class="nav-number">2.</span> <span class="nav-text">MySQL本质了解</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#mysql逻辑架构"><span class="nav-number">2.1.</span> <span class="nav-text">mysql逻辑架构</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#MySQL核心模块"><span class="nav-number">2.1.1.</span> <span class="nav-text">MySQL核心模块</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#存储引擎的区别和选择"><span class="nav-number">2.1.2.</span> <span class="nav-text">存储引擎的区别和选择</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#MySQL-InnoDB的存储文件"><span class="nav-number">2.1.2.1.</span> <span class="nav-text">MySQL InnoDB的存储文件</span></a></li></ol></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#MySQL插件"><span class="nav-number">2.2.</span> <span class="nav-text">MySQL插件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#MySQL中的事务"><span class="nav-number">2.3.</span> <span class="nav-text">MySQL中的事务</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#MysSQL锁表类型"><span class="nav-number">2.4.</span> <span class="nav-text">MysSQL锁表类型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用悲观锁和乐观锁解决并发"><span class="nav-number">2.5.</span> <span class="nav-text">使用悲观锁和乐观锁解决并发</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#悲观锁"><span class="nav-number">2.5.1.</span> <span class="nav-text">悲观锁</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#乐观锁"><span class="nav-number">2.5.2.</span> <span class="nav-text">乐观锁</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#海量数据的分页优化"><span class="nav-number">3.</span> <span class="nav-text">海量数据的分页优化</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#方案"><span class="nav-number">3.1.</span> <span class="nav-text">方案</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#MySQL的安装与配置"><span class="nav-number">4.</span> <span class="nav-text">MySQL的安装与配置</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#MySQL源码安装"><span class="nav-number">4.1.</span> <span class="nav-text">MySQL源码安装</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#MySQL源码目录"><span class="nav-number">4.2.</span> <span class="nav-text">MySQL源码目录</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#数据库配置优化"><span class="nav-number">4.3.</span> <span class="nav-text">数据库配置优化</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#基础配置"><span class="nav-number">4.3.1.</span> <span class="nav-text">基础配置</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#连接数配置"><span class="nav-number">4.3.1.1.</span> <span class="nav-text">连接数配置</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#网络配置"><span class="nav-number">4.3.1.2.</span> <span class="nav-text">网络配置</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#缓存配置"><span class="nav-number">4.3.2.</span> <span class="nav-text">缓存配置</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#查询缓存"><span class="nav-number">4.3.2.1.</span> <span class="nav-text">查询缓存</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#日志配置"><span class="nav-number">4.3.3.</span> <span class="nav-text">日志配置</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#通用查询日志"><span class="nav-number">4.3.3.1.</span> <span class="nav-text">通用查询日志</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#慢查询日志"><span class="nav-number">4.3.3.2.</span> <span class="nav-text">慢查询日志</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#二进制配置"><span class="nav-number">4.3.3.3.</span> <span class="nav-text">二进制配置</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#错误日志"><span class="nav-number">4.3.3.4.</span> <span class="nav-text">错误日志</span></a></li></ol></li></ol></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2012 &mdash; <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">云舒</span>

  

  
</div>




  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/theme-next/hexo-theme-next">NexT.Pisces</a></div>




        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=6.0.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=6.0.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=6.0.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=6.0.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=6.0.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=6.0.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=6.0.4"></script>



  



	





  





  






<!-- LOCAL: You can save these files to your site and update links -->
    
        
         <!-- <link rel="stylesheet" href="https://imsun.github.io/gitment/style/default.css"> -->
        <!-- <script src="https://imsun.github.io/gitment/dist/gitment.browser.js"></script> -->
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/theme-next/theme-next-gitment@1/default.css">
        <script src="https://cdn.jsdelivr.net/gh/theme-next/theme-next-gitment@1/gitment.browser.js"></script>
    
<!-- END LOCAL -->

    

    
      <script type="text/javascript">
      function renderGitment(){
        var gitment = new Gitment({
            id: decodeURI(window.location.pathname),
            owner: 'yunshu2009',
            repo: 'yunshu2009.github.io',
            
            oauth: {
            
            
                client_secret: '15cdd9dc30fb9e0c97260bf79fe09d158fa04b22',
            
                client_id: '9495da16cda475a5e221'
            }});
        gitment.render('gitment-container');
      }

      
      renderGitment();
      
      </script>
    






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  
  

  

  

  

  


</body>
</html>
